package com.experiment.aicommunityback.service.Impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.experiment.aicommunityback.entity.RUutil;
import com.experiment.aicommunityback.entity.Result;
import com.experiment.aicommunityback.entity.ResultCodeEnum;
import com.experiment.aicommunityback.entity.User;
import com.experiment.aicommunityback.mapper.RoleMapper;
import com.experiment.aicommunityback.mapper.UserMapper;
import com.experiment.aicommunityback.service.UserService;
import com.experiment.aicommunityback.util.JwtUtils;
import com.experiment.aicommunityback.util.RoleCompare;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.experiment.aicommunityback.entity.ResultCodeEnum.*;

@Service
public class UserServiceimpl implements UserService {

    /**
     * 头像默认存放地址
     */
    @Value("${default.avatar}")
    private String DEFAULT_AVATAR_LINK;

    /**
     * 添加新用户时默认配置的RoleId
     */
    @Value("${default.newUserRoleId}")
    private int DEFAULT_NEWUSER_ROLEID;

    private UserMapper userMapper;
    private RoleMapper roleMapper;

    @Autowired
    public UserServiceimpl(UserMapper userMapper, RoleMapper roleMapper) {
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
    }

    /**
     * 通过判断是否含有用户和密码是否相等来让用户登录。
     */
    @Override
    public Result getLog(String name, String password) {
        Map<String, Object> map = new HashMap<>();
        map.put("username", name);
        map.put("password", password);
        List<User> users = userMapper.selectByMap(map);
        if (users.size() == 1) {
            users.get(0).setToken(JwtUtils.getToken(name, password));
            Result result = Result.setResult(ResultCodeEnum.LOGIN_SUCCESS);
            Map<String, Object> usermap = new HashMap<>();
            usermap.put("User", users.get(0));
            result.setData(usermap);
            return result;
        } else {
            return Result.setResult(ResultCodeEnum.PASSWOED_ERROR);
        }
    }

    /**
     * 展示用户及其对应权限
     */
    @Override
    public Result showUser() {
        List<User> userList = userMapper.allUser();
        List<RUutil> urlist = userMapper.userOFRole();
        if (userList.isEmpty()) {
            return Result.setResult(UNKNOW_ACCOUNT);
        } else if (urlist.isEmpty()) {
            return Result.error().data("错误原因", "用户-权限表为空");
        } else {
            // 对权限进行选择，同用户只展示最高权限
            List<RUutil> urList = RoleCompare.getBigRole(urlist);
            return Result.ok().data("userList", userList).data("urList", urList);
        }
    }

    /**
     * 添加用户
     */
    @Override
    public Result addUser(User user) {
        if (userMapper.queryByName(user.getName()) != null) {
            return Result.setResult(ResultCodeEnum.QUERY_USER_ERROR).data("错误原因", "用户名重复");
        }
        if (user.getAvatar() == null) {
            user.setAvatar(DEFAULT_AVATAR_LINK);
        }
        if (userMapper.addUser(user)) {
            // 读取用户ID
            int userId = userMapper.nameToUserId(user.getName());
            int defaultRoleId=DEFAULT_NEWUSER_ROLEID;
            // 向UR插入默认权限
            if (!userMapper.addDefaultRole(userId, defaultRoleId)) {
                return Result.setResult(ADD_USER_ERROR).data("错误原因","为用户添加默认权限失败");
            }

            return Result.ok().data("新增的用户名", user.getName());
        } else
            return Result.setResult(ADD_USER_ERROR);
    }

    /**
     * 删除用户
     *
     * @param id 用户id
     */
    @Override
    public Boolean deleteUser(int id) {
        //TODO 需要完成权限删除
        return userMapper.deleteUser(id);
    }

    @Override
    public Result updatedUser(User user) {
        User queryUser = userMapper.queryByName(user.getName());
        if (queryUser != null) {
            return Result.setResult(ResultCodeEnum.QUERY_USER_ERROR).data("错误原因", "用户名重复");
        } else {
            return userMapper.updatedUser(user) ? Result.ok().data("更新用户", true) : Result.setResult(UPDATED_USER_ERROR);
        }
    }

    /**
     * 更新用户状态
     */
    @Override
    public Result updatedUserStatus(Map<String, Object> paramMap) {
        Object status = paramMap.get("status");
        Object id = paramMap.get("id");
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, id).set(User::getStatus, status);
        userMapper.update(null, updateWrapper);
        return null;

    }

    /**
     * <Strong>未实现</Strong><hr>
     * 用户添加权限
     */
    @Override
    public Result userAddRole(int userid, String[] demoData) {
        //TODO 1.删除user=user的行
        userMapper.deleteUR(userid);
        //TODO 2.for循环加入

        return null;
    }

    /**
     * 用户修改权限
     */
    @Override
    public Result userUpdatedRole(int userId, String userRole) {
        int roleId = roleMapper.nameToRoleId(userRole);
        userMapper.userUpdatedRole(userId, roleId);
        return null;
    }

    /**
     * id或name查询用户
     *
     * @param index 查询索引
     * @return user
     */
    @Override
    public User queryUser(String index) {
        // 使用正则表达式判断是id(全数字)还是name，对应不同查询
        if (index.matches("\\d+")) {
            int roleId = Integer.parseInt(index);
            System.out.println( Thread.currentThread().getStackTrace()[1].getFileName()+":查询用户 使用ID查询用户");
            return userMapper.queryById(roleId);
        } else {
            System.out.println(Thread.currentThread().getStackTrace()[1].getFileName()+":查询用户 使用Name查询用户");
            return userMapper.queryByName(index);
        }
    }

    /**
     * 用户Id转用户的roleCode
     *
     * @param userId 用户Id
     */
    @Override
    public String queryRoleCode(int userId) {
        return userMapper.queryRoleCode(userId);
    }
}
